package com.woman.beautylive.presentation.ui.main;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.service.LocationService;
import com.jakewharton.rxbinding.view.RxView;
import com.woman.beautylive.BeautyLiveApplication;
import com.woman.beautylive.R;
import com.woman.beautylive.data.bean.BaseResponse;
import com.woman.beautylive.data.repository.SourceFactory;
import com.woman.beautylive.data.websocket.WebSocketService;
import com.woman.beautylive.domain.AnchorManager;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.base.BaseActivity;
import com.woman.beautylive.presentation.ui.base.BaseObserver;
import com.woman.beautylive.presentation.ui.chatting.utils.FileHelper;
import com.woman.beautylive.presentation.ui.chatting.utils.SharePreferenceManager;
import com.woman.beautylive.presentation.ui.main.me.MeFragment;
import com.woman.beautylive.presentation.ui.main.webview.SimpleWebViewActivity;
import com.woman.beautylive.presentation.ui.room.create.CreateRoomActivity;
import com.woman.beautylive.presentation.ui.widget.MessageDialog;
import com.woman.beautylive.util.L;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    private String ctiyBaiDu;
    private String provinceBaiDu;
    private final MyHandler myHandler = new MyHandler(this);
    @Nullable
    private WebSocketService wsService;

    private ServiceConnection wsConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            L.d(LOG_TAG, "Service connected.");
            wsService = ((WebSocketService.ServiceBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            L.i(LOG_TAG, "Service disconnected.");
        }
    };

    //百度定位服务，只使用一次，用后即焚
    private LocationService locationService;
    private ReportLocationListener mLocationListener = new ReportLocationListener();

    @IdRes
    private static final int FRAG_CONTAINER = R.id.main_container;

    private long lastTimeTapBack = 0;

    private static final String FRAG_TAG_INDEX = "fragIndex";
    private static final String FRAG_TAG_ME = "fragMe";

    private static final String FRAG_TAG_MESSAGE = "fragMessage";
    private static final String FRAG_TAG_FIND = "fragFind";
    private RelativeLayout rlIndex, rlMy, rlFind,rlMessage;

    private IndexFragment indexFragment;
    private MeFragment meFragment;
    private FindFragment findFragment;
    private MessageFragment messageFragment;
    private String mMyName,mMyPassword;
    private Context mContext;
    private static final int REGISTER = 200;
    private boolean r=false;
    private boolean f=false;

    @SuppressWarnings("unused")
    public static Intent createIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    @Override
    protected void init() {
        mContext = this;

        setSwipeBackEnable(false);
        requestLocationAndReport();
        mMyName = "meilibo"+LocalDataManager.getInstance().getLoginInfo().getUserId();
        mMyPassword = "meilibo"+LocalDataManager.getInstance().getLoginInfo().getUserId();

        if (JMessageClient.getMyInfo() == null) {

            for (int i = 0; i < 5; i++) {
                L.e("lw", "注册操作" + i);
                register();
                    if (r = true) {
                        break;
                    }
            }
            if (r=true){
                for (int j = 0; j < 5; j++) {
                    L.e("lw", "登录操作"+j);
                    login();
                    if (f=true) {
                        break;
                    }
                }
            }
        }
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void findViews(Bundle savedInstance) {
        if(savedInstance!=null) {
            savedInstance.clear();
        }
        //预启动WebSocket服务
//        startService(WebSocketService.createIntent(this));
        bindService(WebSocketService.createIntent(this), wsConnection, BIND_AUTO_CREATE);

        rlIndex = $(R.id.main_rl_index);
        rlFind =$(R.id.main_rl_find);
        rlMy=$(R.id.main_rl_my);
        rlMessage=$(R.id.main_re_message);
        ImageButton imgbtnPublishRoom = $(R.id.main_imgbtn_room);
        indexFragment = IndexFragment.newInstance();
        meFragment = MeFragment.newInstance();
        messageFragment=MessageFragment.newInstance();
        findFragment=FindFragment.newInstance();
        getSupportFragmentManager().beginTransaction()
                .add(FRAG_CONTAINER, indexFragment, FRAG_TAG_INDEX)
                .add(FRAG_CONTAINER, messageFragment, FRAG_TAG_MESSAGE)
                .add(FRAG_CONTAINER,findFragment , FRAG_TAG_FIND)
                .add(FRAG_CONTAINER, meFragment , FRAG_TAG_ME)
                .hide(meFragment).hide(messageFragment).hide(findFragment)
                .commit();

        rlIndex.setSelected(true);

        RxView.clicks(rlIndex)
                .filter(new Func1<Void, Boolean>() {
                    @Override
                    public Boolean call(Void aVoid) {
                        //为当前页时直接不处理事件
                        return (!rlIndex.isSelected());
                    }
                })
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        L.v(LOG_TAG, "Tab index : clicked!");
                        rlIndex.setSelected(true);
                        rlMy.setSelected(false);
                        rlMessage.setSelected(false);
                        rlFind.setSelected(false);
                        getSupportFragmentManager().beginTransaction()
                                .hide(meFragment).hide(messageFragment).hide(findFragment)
                                .show(indexFragment)
//                                .replace(FRAG_CONTAINER, fragments[FRAG_INDEX], FRAG_TAG_INDEX)
                                //use this to avoid exception while performing pause.
                                .commitAllowingStateLoss();
                    }
                });

//        开直播的按钮
        subscribeClick(imgbtnPublishRoom, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                startActivity(CreateRoomActivity.createIntent(MainActivity.this,ctiyBaiDu,provinceBaiDu));
//                publishauthority(LocalDataManager.getInstance().getLoginInfo().getToken(),LocalDataManager.getInstance().getLoginInfo().getUserId());
            }
        });

        RxView.clicks(rlMy)
                .filter(new Func1<Void, Boolean>() {
                    @Override
                    public Boolean call(Void aVoid) {
                        //为当前页时直接不处理事件
                        return (!rlMy.isSelected());
                    }
                })
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        L.v(LOG_TAG, "Tab me : clicked!");
                        rlIndex.setSelected(false);
                        rlFind.setSelected(false);
                        rlMessage.setSelected(false);
                        rlMy.setSelected(true);
                        getSupportFragmentManager().beginTransaction()
//                                .replace(FRAG_CONTAINER, fragments[FRAG_ME], FRAG_TAG_ME)
                                .hide(indexFragment).hide(messageFragment).hide(findFragment)
                                .show(meFragment)
                                .commitAllowingStateLoss();
                    }
                });
        RxView.clicks(rlMessage)
                .filter(new Func1<Void, Boolean>() {
                    @Override
                    public Boolean call(Void aVoid) {
                        //为当前页时直接不处理事件
                        return (!rlMessage.isSelected());
                    }
                })
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        L.v(LOG_TAG, "Tab me : clicked!");
                        rlIndex.setSelected(false);
                        rlMy.setSelected(false);
                        rlFind.setSelected(false);
                        rlMessage.setSelected(true);
                        getSupportFragmentManager().beginTransaction()
//                                .replace(FRAG_CONTAINER, fragments[FRAG_ME], FRAG_TAG_ME)
                                .hide(indexFragment).hide(findFragment).hide(meFragment)
                                .show(messageFragment)
                                .commitAllowingStateLoss();
                    }
                });
        RxView.clicks(rlFind)
                .filter(new Func1<Void, Boolean>() {
                    @Override
                    public Boolean call(Void aVoid) {
                        //为当前页时直接不处理事件
                        return (!rlFind.isSelected());
                    }
                })
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        L.v(LOG_TAG, "Tab me : clicked!");
                        rlMy.setSelected(false);
                        rlMessage.setSelected(false);
                        rlIndex.setSelected(false);
                        rlFind.setSelected(true);
                        getSupportFragmentManager().beginTransaction()
//                                .replace(FRAG_CONTAINER, fragments[FRAG_ME], FRAG_TAG_ME)
                                .hide(indexFragment).hide(messageFragment).hide(meFragment)
                                .show(findFragment)
                                .commitAllowingStateLoss();
                    }
                });

//        if (BuildConfig.FLAVOR.equalsIgnoreCase("meilibo")){
//            MessageDialog dialog = new MessageDialog(this);
//            dialog.setContent(R.string.login_brand_tip);
//            dialog.setCancelable(false);
//            dialog.setCanceledOnTouchOutside(false);
//            dialog.show();
//            dialog.hideCancelOption();
//            dialog.setMessageDialogListener(new MessageDialog.MessageDialogListener() {
//                @Override
//                public void onCancelClick(MessageDialog dialog) {
//                    dialog.dismiss();
//                }
//
//                @Override
//                public void onCommitClick(MessageDialog dialog) {
//                    dialog.dismiss();
//                }
//            });
//        }
    }

    /**
     * 自动请求定位并上报
     */
    private void requestLocationAndReport(){
        // -----------location config ------------
        locationService = ((BeautyLiveApplication) getApplication()).locationService;
        locationService.registerListener(mLocationListener);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();// 定位SDK
    }

    /**
     * 尝试关闭定位服务，如果已经关闭则什么也不做。
     */
    private void stopLocationService() {
        if (locationService != null) {
            locationService.unregisterListener(mLocationListener);
            locationService.stop();
            locationService = null;
            mLocationListener = null;
        }
    }

    @Override
    protected void onDestroy() {
        JMessageClient.unRegisterEventReceiver(this);

        UserInfo info = JMessageClient.getMyInfo();
        if (null != info) {
            File file = info.getAvatarFile();
            if (file != null && file.isFile()) {
            } else {
                String path = FileHelper.getUserAvatarPath(info.getUserName());
                file = new File(path);
                if (file.exists()) {
                }
            }
            SharePreferenceManager.setCachedUsername(info.getUserName());
            SharePreferenceManager.setCachedAvatarPath(file.getAbsolutePath());
            JMessageClient.logout();
            L.e("lw", "退出登录");
        }

        super.onDestroy();
        if (wsService != null) {
            wsService.prepareShutdown();
            unbindService(wsConnection);
//            stopService(WebSocketService.createIntent(this));
        }
        stopLocationService();
    }

    @Override
    public void onBackPressed() {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - lastTimeTapBack > 2000) {
            toastShort(R.string.main_tap_to_exit);
            lastTimeTapBack = currentTimeMillis;
        } else {
            UserInfo info = JMessageClient.getMyInfo();
            if (null != info) {
                File file = info.getAvatarFile();
                if (file != null && file.isFile()) {
                } else {
                    String path = FileHelper.getUserAvatarPath(info.getUserName());
                    file = new File(path);
                    if (file.exists()) {
                    }
                }
                SharePreferenceManager.setCachedUsername(info.getUserName());
                SharePreferenceManager.setCachedAvatarPath(file.getAbsolutePath());
                JMessageClient.logout();
                L.e("lw", "退出登录");
            }

                finish();
        }
    }

//    定位的那个回调接口
    private class ReportLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (null != bdLocation && bdLocation.getLocType() != BDLocation.TypeServerError) {
                double lng = bdLocation.getLongitude();//经度
                double lat = bdLocation.getLatitude(); //纬度
                ctiyBaiDu=bdLocation.getCity();
                provinceBaiDu=bdLocation.getProvince();
                L.i(LOG_TAG, "Reporting location:lat=%s, lng=%s", lat, lng);

                new AnchorManager().reportLocation(String.valueOf(lat), String.valueOf(lng))
                        .subscribeOn(Schedulers.io())
                        .subscribe(BaseObserver.<BaseResponse<Object>>silenceObserver());
                //直接关闭
                stopLocationService();
            }
        }
    }

//    是否能直播的签约
    private int PAGER_JSON=1;
    public void publishauthority(String user_token,String user_id) {
//      域名 139.129.19.190
        Request<JSONObject> request = NoHttp.createJsonObjectRequest("http://meilibo.cxtv.kaduoxq.com/OpenAPI/v1/room/canLive", RequestMethod.GET);
//        request.addHeader("apikey", "cafa77120b09d6662ff7a6bdb2d9c149");
        Log.i("mrl",user_token+"    "+user_id);
        request.add("token",user_token);
        request.add("user_id", user_id);

        BeautyLiveApplication.getRequestQueue().add(PAGER_JSON, request, ViewPagerOnResponse);
    }

    private OnResponseListener<JSONObject> ViewPagerOnResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            L.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == PAGER_JSON) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                try {
                    L.i("mrl", result.getString("data"));
                    handler.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            L.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            L.i("lll", "viewpager结束了");
        }
    };

    Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//             *  开启直播验证
//             *
//             *  @param reponse  token  ucid
//             *
//             *  @return 服务器返回 data:( 0 ：可直播；1：未签约；2：时间不对;3:其他错误)
            switch (msg.what){
                case 0:
                    break;
                case 1:
                    showFinishConfirmDialog();
                    break;
                case 2:
                    toastShort("直播时间为： 02:00 - 06:00");
                    break;
                case 3:
                    toastShort("其他错误");
                    break;
            }
        }
    };

//    提示
    public void showFinishConfirmDialog(){
        MessageDialog dialog = new MessageDialog(this);
        dialog.setContent(R.string.mian_sign_tip);
        dialog.setMessageDialogListener(new MessageDialog.MessageDialogListener() {
            @Override
            public void onCancelClick(MessageDialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onCommitClick(MessageDialog dialog) {
                if (dialog!=null && dialog.isShowing()){
                    dialog.dismiss();
                }
//                跳转到签约的url网页中
                startActivity(SimpleWebViewActivity.createIntent(MainActivity.this,
                        SourceFactory.wrapPath("http://meilibo.cxtv.kaduoxq.com/app/goodvoice")));
            }
        });
        dialog.show();
    }

    public void login() {
        JMessageClient.login(mMyName, mMyPassword, new BasicCallback() {
            @Override
            public void gotResult(int status, String desc) {
                if (status == 0) {
                    L.e("lw","登录成功");
                    f=true;
                } else {
                    L.e("lw","登录失败"+status+desc);
                }
            }
        });
    }

    public void register() {
        JMessageClient.register(mMyName, mMyPassword, new BasicCallback() {
            @Override
            public void gotResult(int status, String desc) {
                if (status == 0) {
                    L.e("lw","注册成功");
                    r=true;
                } else {
                    L.e("lw", "注册失败" + status + desc);
                    if (desc.equals("user exist")) {
                        r=true;
                    }
                }
            }
        });
    }

    @Override
    protected void onPause() {
        JPushInterface.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        JPushInterface.onResume(this);
        super.onResume();
    }

    private static class MyHandler extends Handler {

        private WeakReference<MainActivity> mActivity;

        public MyHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity mainActivity = mActivity.get();
            if (mainActivity != null) {
                switch (msg.what) {
                    case REGISTER:
                        mainActivity.login();
                        break;
                }
            }
        }
    }
}